const appId = "wx69b48d6eda852d25"
const appSecret = 'd6111d274ba5ca9112baa06074148833'
const jwt = require('jsonwebtoken')

function getToken(openid) {
  return jwt.sign({
    openid
  }, appSecret, {
    expiresIn: 60 * 60 * 24
  })
}

function verifyToken(token) {
  return jwt.verify(token, appSecret)
}
const db = uniCloud.database();
async function requestNewAccessToken() {
  const res = await uniCloud.httpclient.request(
    "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" +
    appSecret, {
      dataType: "json"
    });
  console.log("重新请求accesstoken");


  const dbRes = await db.collection("system").limit(1).get();

  if (dbRes.data[0]) {
    await db.collection("system").doc(dbRes.data[0]._id).update({
      accesstoken: {
        value: res.data.access_token,
        expiredtime: new Date().getTime() + 7000000
      }
    });
  } else {
    await db.collection("system").add({
      accesstoken: {
        value: res.data.access_token,
        expiredtime: new Date().getTime() + 7000000
      }
    });
  }

  return res.data.access_token;
}
async function getAccessToken(forceupdate = false) {
  const dbRes = await db.collection("system").limit(1).get();
  const systemInfo = dbRes.data[0];

  const now = new Date().getTime();
  if (systemInfo && !forceupdate) {
    if (now > systemInfo.accesstoken.expiredtime) {
      const accesstoken = await requestNewAccessToken();

      return accesstoken;
    } else {
      console.log("使用缓存的accesstoken");
      return systemInfo.accesstoken.value;
    }
  } else {
    const accesstoken = await requestNewAccessToken();

    return accesstoken;
  }
}
//https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=
async function getWXACodeUnlimited(scene, page) {
  const access_token = await getAccessToken();
  const res = await uniCloud.httpclient.request("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" +
    access_token, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      data: {
        scene: scene,
        page: page
      }
    });

  return res.data;
}
module.exports = {
  // 公用模块用法请参考 https://uniapp.dcloud.io/uniCloud/cf-common
  appId,
  appSecret,
  getToken,
  verifyToken,
  getWXACodeUnlimited
}
